package com.maodou.android.viewmodel.login

import androidx.lifecycle.viewModelScope
import com.maodou.android.data.model.EmailRegisterParams
import com.maodou.android.data.remote.UserRepository
import com.maodou.android.ui.page.MainKey
import com.maodou.android.utils.PublicUtils.isEmail
import com.maodou.core.base.BaseViewModel
import com.maodou.core.datastore.DataStore
import com.maodou.core.manager.GlobalStateManager
import com.maodou.android.data.model.EmailCodeResult
import com.maodou.core.model.UserInfo
import com.maodou.core.navigation.GlobalUiBus
import com.maodou.core.navigation.Navigator3
import com.maodou.core.network.handleResult
import com.maodou.core.network.toUserMessage
import com.maodou.core.utils.Logger
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
import kotlinx.coroutines.delay
import kotlinx.coroutines.Job

/**
 * @Author Xing
 * @CreateTime 2025年08月27日
 * @Description 登录注册等功能业务处理
 */
data class LoginUiState(
    val isLoading: Boolean = false,
    val timeCount: Int = 60,
    val isVerificationCodeSending: Boolean = false,
)

/**
 *  UI 事件
 */
sealed interface LoginUiEvent {
    data class ShowError(val message: String) : LoginUiEvent
}

@HiltViewModel
class LoginViewModel @Inject constructor(
    private val globalStateManager: GlobalStateManager,
    private val repository: UserRepository,
    private val dataStore: DataStore
) : BaseViewModel<LoginUiState, LoginUiEvent>() {

    private var countDownJob: Job? = null

    override fun createInitialState(): LoginUiState {
        return LoginUiState()
    }

    override fun setLoading(isLoading: Boolean) {
        updateUiState { it.copy(isLoading = isLoading) }
    }

    fun onLogin(email: String, pwd: String){
        viewModelScope.launch {
            repository.onUserLogin(email, pwd).handleResult(
                onSuccess = {
                    viewModelScope.launch {
                        globalStateManager.setLoginState(true,it.apiKey,it)
                        Navigator3.resetToWithFade(MainKey)
                    }
                },
                onError = { error ->
                    viewModelScope.launch {
                        globalStateManager.setLoginState(true,"it.apiKey", UserInfo("777777777777777"))
                        Navigator3.resetToWithFade(MainKey)
                    }
                    Logger.d("请求失败=${error.toUserMessage()}")
                },
                onLoading = {
                    setLoading(it)
                }
            )
        }
    }

    fun onSendCode(email: String){
        viewModelScope.launch {
            repository.getEmailCode(email).handleResult(
                onSuccess = {
                    dataStore.keyValue.putObject("REGISTER_TOKEN",it, EmailCodeResult::class.java)
                    startVerificationCountDown()
                },
                onError = { error ->
                    startVerificationCountDown()
                    Logger.d("请求失败=${error.toUserMessage()}")
                },
                onLoading = { loading ->
                    updateUiState {
                        it.copy(
                            isVerificationCodeSending = loading
                        )
                    }
                }
            )
        }
    }

    private fun startVerificationCountDown() {
        countDownJob?.cancel()
        countDownJob = viewModelScope.launch {
            var sec = 60
            updateUiState { it.copy(timeCount = 59) }
            while (sec > 0) {
                delay(1000)
                sec--
                if(sec == 0) countDownJob?.cancel()
                updateUiState { it.copy(timeCount = sec) }
            }
            updateUiState { it.copy(timeCount = 60) }
        }
    }

    fun onRegister(registerParams: EmailRegisterParams){
        if(!isEmail(registerParams.email)){
            GlobalUiBus.showToast("请正确输入邮箱")
        } else if((registerParams.code ?: "").length < 4){
            GlobalUiBus.showToast("请正确输入验证码")
        } else if((registerParams.password ?: "").length < 6 || (registerParams.confirmPassword ?: "").length < 6){
            GlobalUiBus.showToast("建议密码是6-20位字符")
        } else if(registerParams.password != registerParams.confirmPassword){
            GlobalUiBus.showToast("两次密码不一致")
        } else viewModelScope.launch {
            val emailToken = dataStore.keyValue.getObject("REGISTER_TOKEN",EmailCodeResult::class.java)
            registerParams.token = if(registerParams.email == emailToken?.email) emailToken?.token else null
            repository.onUserRegister(registerParams).handleResult(
                onSuccess = {
                    viewModelScope.launch {
                        globalStateManager.setLoginState(true,it.apiKey,it)
                        Navigator3.resetToWithFade(MainKey)
                    }
                },
                onError = { error ->
                    Logger.d("请求失败=${error.toUserMessage()}")
                },
                onLoading = { loading ->
                    updateUiState {
                        it.copy(
                            isLoading = loading
                        )
                    }
                }
            )
        }
    }

    override fun onCleared() {
        countDownJob?.cancel()
        super.onCleared()
    }
}